package com.ludaxu.google.manager;

import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 管理线程池
 * 
 * @author ludaxu
 * 
 */
public class ThreadManager {
	private static ThreadManager instance = new ThreadManager();
	private ThreadPoolProxy longPool;
	private ThreadPoolProxy shortPool;

	// 整个应用程序只有一个线程管理者,单例模式
	private ThreadManager() {

	}

	public static ThreadManager getInstance() {
		return instance;
	}

	// 联网比较耗时

	// cpu的核数*2+1
	public synchronized ThreadPoolProxy createLongPool() {
		if (longPool == null) {
			longPool = new ThreadPoolProxy(5, 5, 5000L);
		}

		return longPool;
	}

	// 读取本地文件
	public synchronized ThreadPoolProxy createShortPool() {
		if (shortPool == null) {
			shortPool = new ThreadPoolProxy(3, 3, 5000L);
		}

		return shortPool;
	}

	public class ThreadPoolProxy {
		private ThreadPoolExecutor pool;
		private int corePoolSize;
		private int maximumPoolSize;
		private long time;

		public ThreadPoolProxy(int corePoolSize, int maximumPoolSize, long time) {
			this.corePoolSize = corePoolSize;
			this.maximumPoolSize = maximumPoolSize;
			this.time = time;
		}

		public void execute(Runnable runnable) {
			if (pool == null) {
				// 创建线程池
				/***
				 * 1.线程池可用管理多少个线程 2.如果排队满了,额外的开的线程数 3.如果线程池没有要执行的任务了,存活多久
				 * 4.存活时间的单位
				 * 5.如果线程池里管理的线程都已经用了,剩下的任务都先临时存到LinkedBlockingDeque对象中排队(最多10个)
				 */
				pool = new ThreadPoolExecutor(corePoolSize, maximumPoolSize,
						time, TimeUnit.MILLISECONDS,
						new LinkedBlockingDeque<Runnable>(10));
			}
			pool.execute(runnable);// 调用线程池,执行异步任务
		}

		public void cancel(Runnable runnable) {
			// 线程池崩溃,线程池停止
			if (pool != null && !pool.isShutdown() && !pool.isTerminated()) {
				pool.remove(runnable);// 移除一个任务
			}
		}
	}

}
